import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import * as types from '@/store/mutations_types'
import home from '@/pages/home/index'
// import home from '@/pages/shop/children/home'

Vue.use(Router)

// 教练员
const coach = r => require.ensure([], () => r(require('@/pages/coach/index')), 'coach')
const coachHome = r => require.ensure([], () => r(require('@/pages/coach/children/home')), 'coachHome')
// 文章
const article = r => require.ensure([], () => r(require('@/pages/article/index')), 'article')
const articleView = r => require.ensure([], () => r(require('@/pages/article/children/view')), 'articleView')
// 课程
const course = r => require.ensure([], () => r(require('@/pages/article/index')), 'article')
const courseHome = r => require.ensure([], () => r(require('@/pages/course/children/home')), 'courseHome')

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: home
      // meta: { keepAlive: true }
    },
    {
      path: '/coach',
      component: coach,
      children: [
        {
          path: '',
          component: coachHome
          // meta: { keepAlive: true }
        }
      ]
    },
    {
      path: '/article',
      component: article,
      children: [
        {
          path: 'view/:id',
          component: articleView
          // meta: { keepAlive: true }
        }
      ]
    },
    {
      path: '/course',
      component: course,
      children: [
        {
          path: '',
          component: courseHome
          // meta: { keepAlive: true }
        }
      ]
    }
  ]
})

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)

router.beforeEach((to, from, next) => {
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit(types.UPDATE_DIRECTION, {direction: 'forward'})
    } else {
      store.commit(types.UPDATE_DIRECTION, {direction: 'reverse'})
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit(types.UPDATE_DIRECTION, {direction: 'forward'})
  }
  next()
})

export default router
